﻿using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Common.EFCore;
using Hicap.AuthorizationServer.Core.Models;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Abp.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Hicap.AuthorizationServer.Core.Managers
{
    public class CompanyManager : ManagerBase<Company>, ICompanyManager
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public CompanyManager(IUnitOfWork unitOfWork, IAbpSession session, IHostingEnvironment hostingEnvironment) : base(unitOfWork)
        {
            _hostingEnvironment = hostingEnvironment;
            QueryCondition.Add(x => x.IsDeleted == false);
            CreateActions.Add(x => x.CreatorUserId = session.UserId);
            CreateActions.Add(x => x.CreationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModificationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModifierUserId = session.UserId);
            DeleteActions.Add(x => x.DeletionTime = DateTime.Now);
            DeleteActions.Add(x => x.DeleterUserId = session.UserId);
            DeleteActions.Add(x => x.IsDeleted = true);

            CreateCheckActions.Add(x =>
            {
                if (x.Id == 0) return true;
                Log.Warning($"Company CreateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            UpdateCheckActions.Add(x =>
            {
                if (x.Id > 0 && x.IsDeleted == false) return true;
                Log.Warning($"Company UpdateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            DeleteCheckActions.Add(x =>
            {
                if (x.IsDeleted == false) return true;
                Log.Warning($"Company DeleteCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
        }

        public async Task<List<Company>> GetAllCompanys()
        {
            return await Repository.GetAllListAsync();
        }

        public Company GetImage(int input)
        {
            return Repository.Get(input);
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="files"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public string UploadImg([FromForm]IFormFile files, int id)
        {
            var base64Name = "";
            //var webRootPath = _hostingEnvironment.WebRootPath;
            var filePath = SysConsts.ImagePath;

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            if (files != null)
            {
                //文件后缀
                var fileExtension = Path.GetExtension(files.FileName);
                //判断后缀是否是图片
                const string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|.bmp|.ico|......";
                if (fileExtension == null)
                {
                    throw new UserFriendlyException("上传的文件没有后缀");
                }

                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    throw new UserFriendlyException("上传的文件不是图片");
                }

                //判断文件大小
                long length = files.Length;
                if (length > 1024 * 1024 * 2) //2M
                {
                    throw new UserFriendlyException("上传的文件不能大于2M");
                }

                using (FileStream fs = File.Create(filePath + files.FileName))
                {
                    files.CopyTo(fs);
                    fs.Flush();
                    byte[] bytes = Encoding.UTF8.GetBytes(files.FileName);

                    base64Name = Convert.ToBase64String(bytes);
                    Company model = new Company
                    {
                        CompanyLogo = base64Name,//FileToBase64(filePath + saveName),
                        Id = id
                    };
                    Repository.Update(model);
                    UnitOfWork.SaveChanges();
                }
            }

            return base64Name;
        }

        /// <summary>
        /// 将base64格式，转换utf8
        /// </summary>
        /// <param name="base64String">解密内容</param>
        /// <returns></returns>
        public string Base64Decode(string base64String)
        {
            byte[] bytes = Convert.FromBase64String(base64String);
            return Encoding.UTF8.GetString(bytes);
        }
    }
}